﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ZooKeeperNet;
using Org.Apache.Zookeeper.Data;
using ZK = ZooKeeperNet;

using WorkStation.Frameworks.Core;
using WorkStation.Frameworks.Core.Extensions;
using WorkStation.Frameworks.EasyBus.DbModel;
using WorkStation.Frameworks.EasyBus.Repositories;

using Newtonsoft.Json;

namespace WorkStation.Frameworks.EasyBus.Repositories.ZooKeeper
{
    public class ListenerInfoChangeWatcher : IWatcher
    {
        protected IBus _bus;
        protected ZK.ZooKeeper _zk;

        public ListenerInfoChangeWatcher(IBus bus, ZK.ZooKeeper zk) 
        {
            this._bus = bus;
            this._zk = zk;
        }

        public void Process(WatchedEvent @event)
        {
            // 连接断开和会话失效不做处理
            switch (@event.State) 
            {
                case KeeperState.Disconnected:
                case KeeperState.Expired:
                    return;
            }

            IBusDataManager manager = this._bus as IBusDataManager;

            Stat stat = this._zk.Exists(@event.Path, false);

            // 监听信息变更事件
            if (@event.Type == EventType.NodeDataChanged) 
            {
                ListenerInfo info = this._zk.GetData(@event.Path, new ListenerInfoChangeWatcher(this._bus, this._zk), stat).ZooNodeToObject<ListenerInfo>();

                this._bus.Publish(new ListenerInfoChangeEvent() { Change = info, ListenerInfoChangeType = ListenerInfoChangeTypeEnum.Change });
            }
        }
    }
}
  